<template>
  <el-card style="max-width: 500px; margin: 0 auto;">
    <h2>修改个人信息</h2>
    <el-form :model="form" label-width="80px" ref="formRef">
      <el-form-item label="学号">
        <el-input v-model="form.stuId" disabled />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="form.name" disabled />
      </el-form-item>
      <el-form-item label="积分">
        <el-input v-model="form.point" disabled />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="form.phone" placeholder="请输入电话" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const stuId = localStorage.getItem('loginId')
const form = ref({
  stuId: '',
  name: '',
  email: '',
  phone: '',
  point: 0
})
const originForm = ref({})

const getStudentInfo = async () => {
  try {
    const res = await axios.get(`http://localhost:8080/student/getStudent/${stuId}`)
    if (res.data && res.data.code === 200 && res.data.data) {
      form.value = {
        stuId: res.data.data.stuId,
        name: res.data.data.name,
        email: res.data.data.email,
        phone: res.data.data.phone,
        point: res.data.data.point
      }
      originForm.value = { ...form.value }
    } else {
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '获取信息失败')
    }
  } catch (e) {
    ElMessage.error('获取信息失败')
  }
}

onMounted(getStudentInfo)

const submitForm = async () => {
  try {
    const res = await axios.put(
      `http://localhost:8080/student/${form.value.stuId}/editInfo`,
      {
        "stuId": Number(form.value.stuId),
        "name": form.value.name,
        "email": form.value.email,
        "phone": form.value.phone,
        "point": form.value.point
      }
    )
    if (res.data && res.data.code === 200) {
      ElMessage.success('信息修改成功')
      getStudentInfo()
    } else {
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '保存失败')
    }
  } catch (e) {
    ElMessage.error('保存失败')
  }
}

const resetForm = () => {
  form.value.email = originForm.value.email
  form.value.phone = originForm.value.phone
}
</script>